package com.cj.cms.dao.security;

import org.springframework.stereotype.Repository;

import com.cj.cms.entity.Channel;
import com.cj.cms.entity.WebSite;
import com.cj.common.orm.hibernate.HibernateDao;
import com.cj.sys.service.ServiceException;

@Repository
public class ChannelDao extends HibernateDao<Channel, Long> {
	@Override
	public void save(Channel entity) {
		if(entity.getParent() != null && entity.getParent().getId() == null){
			entity.setParent(null);
		}
		if(entity.getWebSite() == null || entity.getWebSite().getId() == null)
			entity.setWebSite(new WebSite(1L));
		if(entity.getParent() != null){
			Channel parent = this.load(entity.getParent().getId());
			entity.setFullName(parent.getFullName() + "/" + entity.getCode());
			if(entity.getParent().getId().equals(entity.getId()))
				throw new ServiceException("上级栏目不能为自己!");
		}else
			entity.setFullName("/" + entity.getCode());
		if(entity.getTemplate() != null && entity.getTemplate().getId() == null)
			entity.setTemplate(null);
		if(entity.getContentTemplate() != null && entity.getContentTemplate().getId() == null)
			entity.setContentTemplate(null);
		if(entity.getPertainTemplate() != null && entity.getPertainTemplate().getId() == null)
			entity.setPertainTemplate(null);

		if(isPropertyUniqueById("code", entity.getCode(), entity.getId()))
			super.save(entity);
		else
			throw new ServiceException("栏目代码已存在！" + entity.getCode());
	}
}
